<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/28
 * Time: 11:19
 */

class Auto extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $days = $this->getSetting();
        $rows = $this->getOrders($days);
        if (!empty($rows)) foreach ($rows as $row) {
            $this->updateOrder($rows['id']);
        }
    }

    public function updateOrder($id)
    {
        $db = clone($this->db);
        $db->where('id', $id);
        $db->update('user_order', [
            'status' => 'Complete',
            'compTime' => date('Y-m-d H:i:s'),
            'merge' => 0
        ]);
    }

    public function getOrders($days = 15)
    {
        $startTime = date('Y-m-d 00:00:00', strtotime("-{$days} days"));
        $endTime = date('Y-m-d 23:59:59', strtotime("-{$days} days"));

        $db = clone($this->db);
        $q = $db->get_where('user_order', [
            'created >=' => $startTime,
            'created <=' => $endTime,
            'status' => 'Dispatch'
        ]);
        return $q->result_array();
    }

    /**
     * @return int
     */
    private function getSetting()
    {
        $db = clone($this->db);
        $q = $db->get_where('setting', ['use' => 'system', 'key' => 'autoDays']);
        $item = $q->row_array();
        if (empty($item)) {
            return 15;
        }
        return intval($item['value']);
    }
}